package org.tinygame.herostory.handler;

import io.netty.channel.ChannelHandlerContext;
import io.netty.util.AttributeKey;
import org.tinygame.herostory.BroadCaster;
import org.tinygame.herostory.mode.User;
import org.tinygame.herostory.mode.UserManager;
import org.tinygame.herostory.msg.GameMsgProtocol;

public class UserEntryHandler implements ICmdHandler<GameMsgProtocol.UserEntryCmd> {

    /**
     * 登录 - 英雄进场
     * @param ctx
     * @param msg
     */
    @Override
    public void handler(ChannelHandlerContext ctx, GameMsgProtocol.UserEntryCmd msg) {
        //从指令对象中获取用户id和英雄形象
        GameMsgProtocol.UserEntryCmd cmd = msg;
        int userId = cmd.getUserId();//用户ID
        String avatar = cmd.getHeroAvatar();//英雄形象

        GameMsgProtocol.UserEntryResult.Builder resultBuilder = GameMsgProtocol.UserEntryResult.newBuilder();
        resultBuilder.setUserId(userId);
        resultBuilder.setHeroAvatar(avatar);

        //添加用户
        User user = new User(userId,avatar);
        user.setHp(100);//用户进入，血量100
        UserManager.addUser(user);

        //将用户ID 附着到channel上
        ctx.channel().attr(AttributeKey.valueOf("userId")).set(userId);

        //群发
        GameMsgProtocol.UserEntryResult newResult = resultBuilder.build();
        BroadCaster.broadCaster(newResult);
    }
}
